<!--
- File:    租花确认订单.
-->
<template>
  <div>
    <div class="Web_Box">
      <div class="con_tab" v-show="false">
        <ul class="f-cb">
          <li class="bor-r-ddd" :class="{'cur': type == 0}" @click="switchType(0)">邮寄</li>
          <li :class="{'cur': type == 1}" @click="switchType(1)">自提</li>
        </ul>
      </div>
      <div class="ConfirmationOrder">
        <div class="ConsigneeInfo" v-show="type == 0">
          <div class="add_adree" v-show="addressList.requested && addressList.data.length <= 0" @click="gotoAddAddress">添加收货地址</div>
          <div v-show="addressList.requested && addressList.data.length > 0" @click="selectAddress">
            <p class="text1 f-cb"><span class="name fl">收货人:{{address.true_name}} </span>
              <span class="tel fr">{{address.mob_phone}}</span></p>
            <div class="Address slh2">{{address.area_info}} {{address.address}}</div>
            <i class="iconfont icon-more" style="position: absolute; right: 0.5rem; top: 50%; width: 0.575rem; height: 0.575rem; line-height: 0.575rem; font-size: 0.575rem; color: #898989; -webkit-transform: translate(0, -50%); "></i>
          </div>
        </div>
        <div class="ConsigneeInfo" style="background: #fff; margin-bottom: 0.25rem" v-show="type == 1">
          <div class="add_adree" v-show="shopAddressList.requested && shopAddressList.data.length <= 0">当前无线下商店数据，暂不能自提</div>
          <div v-show="shopAddressList.requested && shopAddressList.data.length > 0" @click="selectShopAddress">
            <p class="text1 f-cb">
              <span class="name fl"><span class="cr_f23030 pr5">自提门店</span> {{shopAddress.seller_name}} </span>
              <span class="tel fr">{{shopAddress.telphone}}</span></p>
            <div class="Address slh2">{{shopAddress.area_info}} {{shopAddress.address}}</div>
            <i class="iconfont icon-rightdot"></i></div>
        </div>
        <div class="ShopGoods EditPro hidden bor_b_dcdddd">
          <div class="ProList">
            <!--<div class="oeder_tex">订单号:2362356239521521</div>-->
            <div class="oeder_tex"><i class="iconfont icon-dianpu"></i><span>{{rentInfo.store_name}}</span></div>
            <ul>
              <li v-for="item in rentInfo.alldata">
                <!--<div class="tisb" v-show="item.is_voucher == '0'">此商品不可用优惠券</div>-->
                <div class="Pic">
                  <img :src="$config.imgsite + $config.goodsImgSrc + item.store_id + '/' + item.goods_image + '_w150'" alt=""/>
                </div>
                <div class="Con">
                  <div class="pl20">
                    <h2 class="">{{item.goods_name}}
                      <!--&nbsp;&nbsp;<span v-for="attr in item.goods_spec">{{attr.name}} </span>-->
                    </h2>
                    <!--<p class="Attribute"><span v-for="attr in item.goods_spec">{{attr.name}} </span></p>-->
                    <p class="PriceQuantity">
                      <span class="fl cr_f84e37">￥{{item.goods_price | discount(item.groupbuy_rebate)}}</span><span class="fr cr_282828">×{{item.goods_num}}</span>
                    </p>
                  </div>
                </div>
              </li>
              <li>
                <p style="font-size: 14px">合计:<span class="cr_f84e37">￥{{rentInfo.total}}/月</span>
                </p></li>
            </ul>
          </div>
        </div>
        <div class="OtherInfo">
          <ul>
            <li v-show="false">
              <div class="tit">可使用余额支付 </div>
              <div class=" pr50">
                <span class="cr_fd6847 ml10">￥{{balanceUsed | toFixed(2)}}</span>
                <!--<span class="ml10">(总余额:￥{{rentInfo.balance}})</span>-->
              </div>
              <i v-show="!useBalance" class="iconfont icon-pitch2" @click="switchUseBalance(true)"></i>
              <i v-show="useBalance" class="iconfont icon-select" @click="switchUseBalance(false)"></i></li>

            <li>
              <div class="tit">配送方式</div>
              <div class="fr pr20 f24 cr_000">送货上门</div>
              <!--<i class="iconfont icon-rightdot2"></i></li>-->
            <li class="Total" style=" height:80px;"><textarea placeholder="买家留言" v-model="remark"></textarea></li>
          </ul>
        </div>
      </div>
      <!--租花填写资料-->
      <div class="Fillinformation">
        <div class="Fill_input f-cb">
          <label>期望入驻时间(必填)<span type="text" @click="openRentDatePicker" style="float: right">{{rentInfoEdit.date}}</span></label>
        </div>
        <div class="Fill_input f-cb">
          <i class="iconfont icon-triangle"></i>
          <label>所属行业
            <select v-model="rentInfoEdit.trade">
              <option selected value="">请选择</option>
              <option v-for="trade in rentInfo.scene_industry" :value='trade.d_id' v-if="trade.d_type_id == 'industry'">{{trade.d_name}}</option>
            </select>
          </label>
        </div>
        <div class="Fill_input f-cb">
          <i class="iconfont icon-triangle"></i><label>摆放场景<select v-model="rentInfoEdit.place">
          <option selected value="">请选择</option>
          <option v-for="trade in rentInfo.scene_industry" :value='trade.d_id' v-if="trade.d_type_id == 'scene'">{{trade.d_name}}</option>
        </select></label></div>
        <div class="Fill_input f-cb"><label>公司名称<input type="text" v-model="rentInfoEdit.company" placeholder="输入公司名称"></label>
        </div>
        <!--<div class="Fill_input f-cb"><label>联系电话<input type="tel" v-model="rentInfoEdit.tel"></label></div>-->
        <div class="Fill_input f-cb">
          <label>场地面积(m²)<input type="text" v-model="rentInfoEdit.square" placeholder="如:50-100" style="width: 7.5rem"></label>
        </div>
        <div class="Fill_input f-cb">上传场地平面图、场地实景图
          <div class="fll_price2 f-cb">
            <div class="fllimg">
              <div id="select-pic">
                <input id="fileInput1" accept="image/jpeg,image/jpg,image/png,image/gif" type="file" style="display: none" @change="fileSelected">
              </div>
              <i class="iconfont icon-tianjia1" @click="getImg" style="pointer-events: auto;"></i>
            </div>
            <div class="fllimg" v-for="(img, imgIndex) in rentInfoEdit.placeImg" @click="delImg(imgIndex)">
              <img :src="$config.imgsite + $config.uploadImgSrc + img + '_w200'"></div>
          </div>
        </div>

        <div class="Fill_input2">温馨提醒：订单起租价500元，至少租3个月</div>
        <div class="Fill_input f-cb">
          <i class="iconfont icon-triangle"></i><label>租用时长(必填)<select v-model="rentInfoEdit.rentTerm">
          <option selected value="">请选择</option>
          <option value="3">3个月</option>
          <!--<option value="4">4个月</option>-->
          <!--<option value="5">5个月</option>-->
          <option value="6">6个月</option>
          <!--<option value="7">7个月</option>-->
          <!--<option value="8">8个月</option>-->
          <option value="9">9个月</option>
          <!--<option value="10">10个月</option>-->
          <!--<option value="11">11个月</option>-->
          <option value="12">12个月</option>
          <!--<option value="13">13个月</option>-->
          <!--<option value="14">14个月</option>-->
          <option value="15">15个月</option>
          <!--<option value="16">16个月</option>-->
          <!--<option value="17">17个月</option>-->
          <option value="18">18个月</option>
          <!--<option value="19">19个月</option>-->
          <!--<option value="20">20个月</option>-->
          <option value="21">21个月</option>
          <!--<option value="22">22个月</option>-->
          <!--<option value="23">23个月</option>-->
          <option value="24">24个月</option>
        </select></label></div>
        <div class="Fill_input f-cb">
          <i class="iconfont icon-triangle"></i><label>付款方式(必填)<select v-model="rentInfoEdit.installment">
          <option value="0" selected>全款</option>
          <option value="2" v-if="ifValidInstallMonth(rentInfoEdit.rentTerm, 2)">2期</option>
          <option value="3" v-if="ifValidInstallMonth(rentInfoEdit.rentTerm, 3)">3期</option>
          <option value="4" v-if="ifValidInstallMonth(rentInfoEdit.rentTerm, 4)">4期</option>
          <option value="5" v-if="ifValidInstallMonth(rentInfoEdit.rentTerm, 5)">5期</option>
          <option value="6" v-if="ifValidInstallMonth(rentInfoEdit.rentTerm, 6)">6期</option>
          <option value="7" v-if="ifValidInstallMonth(rentInfoEdit.rentTerm, 7)">7期</option>
          <option value="8" v-if="ifValidInstallMonth(rentInfoEdit.rentTerm, 8)">8期</option>
          <!--<option value="9" v-show="rentInfoEdit.rentTerm >= 9">9期</option>-->
          <!--<option value="12" v-show="rentInfoEdit.rentTerm >= 12">12期</option>-->
        </select></label>
        </div>
        <div class="Fill_input f-cb" v-if="rentInfoEdit.rentTerm != ''">
          <div class="fll_price">
            <p class="pt10">商品租金: {{rentInfo.total}}X{{rentInfoEdit.rentTerm}}个月 = <span :class="{'cr_fd6847': rentInfoEdit.installment == 0}">￥{{(rentInfo.total * rentInfoEdit.rentTerm).toFixed(2)}}</span>
            </p>
            <!--<p class="pt10">订单总额：<span class="cr_f60202">￥{{orderTotalMoney}}</span></p>-->
            <!--<p class="pt10" v-show="rentInfoEdit.installment != 0">本次需支付：首期租金￥{{installment}} 和押金￥{{deposit}}</p>-->
            <div class="OtherInfo">
              <ul>
                <li>
                  <p class="f-cb">优惠券<span class="fr Clip" @click="switchCouponShow(true)"><span class="ml10" :class="{'cr_fd6847': rentInfoEdit.installment == 0}" v-if="selectedCoupon && selectedCoupon.voucher_price">-￥{{selectedCoupon.voucher_price}}</span><span v-show="!selectedCoupon && canUseCouponNum > 0">使用</span><span v-show="!selectedCoupon && canUseCouponNum <= 0" class=" cr_898989">无可用优惠券</span><i class="iconfont icon-more"></i></span>
                  </p>
                </li>
                <!--<li class="" v-if="selectedCoupon">-->
                <!--<div class="tit">优惠券优惠金额：<span class="cr_fd6847 ml10">￥{{selectedCoupon.voucher_price}}</span>-->
                <!--<span style="float: right; color: #999; padding-right: 14px" @click="cancleUseCoupon">取消使用</span>-->
                <!--</div>-->
                <!--</li>-->
                <li style="height:55px; position: relative" v-if="!selectedCoupon">
                  <div class="tit">可用积分抵扣 <span class="ml10" :class="{'cr_fd6847': useIntegral && rentInfoEdit.installment == 0}">-￥{{integralUsed | toFixed(2)}}</span>
                    <i v-show="!useIntegral" class="iconfont icon-pitch2" style="position: absolute; right: 0; top: 10px; font-size: 20px;" @click="switchIntegral(true)"></i>
                    <i v-show="useIntegral" class="iconfont icon-pitchon2" style="position: absolute; right: 0; top: 10px; font-size: 20px;" @click="switchIntegral(false)"></i>
                    <p class="f12 cr_898989">积分最多可抵扣订单总额的{{couponSetting.points_orderrate * 100}}%</p>
                  </div>
                </li>
              </ul>
            </div>
            <p class="pt10" v-show="rentInfoEdit.installment != 0">分期支付：<span class="cr_f60202">{{installmentMoney | toFixed(2)}}</span>X{{rentInfoEdit.installment}}期
            <p class="pt10">押金2个月：<span class="cr_fd6847">￥{{deposit | toFixed(2)}}</span></p>
          </div>
        </div>
      </div>
      <!--填写资料 end-->
    </div>
    <div class="BottomGd" style="z-index: 99">
      <span class="totals">合计支付:<span class="cr_fd6847" v-show="payed != ''">￥{{payed | toFixed(2)}}</span></span>
      <button class="but_3 fr bg_45a73a" type="button" @click="submitOrder">提交订单</button>
    </div>
    <!--使用优惠券弹窗-->
    <div class="coupbg" v-show="couponModelShow">
      <div class="PopBg" @click="switchCouponShow(false)"></div>
      <div class="coupon_box" style="z-index: 99; max-height: 10rem; overflow-y: scroll">
        <div v-show="rentInfo.voucher_list && rentInfo.voucher_list.length > 0">
          <!--<h3>使用优惠券</h3>-->
          <p class="f-cb pl20">支持优惠券的订单金额：<span>￥{{rentInfo.voucher_goods_total * rentInfoEdit.rentTerm}}</span></p>
          <div class="couponlist f-cb" style="height: 5rem; background-size: 100% 5rem" :class="{'coupon-selected': (selectedCoupon && coupon.voucher_id == selectedCoupon.voucher_id)}" v-for="coupon in rentInfo.voucher_list" v-show="coupon.voucher_type == $dictionary.couponType.rent">
            <div class="fl">
              <p class="c_class">类型：{{coupon.voucher_type | couponTypeTxt}}</p>
              <p class="c_time">{{coupon.voucher_start_date | timestampToDate('yyyy.MM.dd')}}-{{coupon.voucher_end_date | timestampToDate('yyyy.MM.dd')}}</p>
              <p class="c_money">{{coupon.voucher_limit | couponUseTxt}}</p>
            </div>
            <div class="fr">
              <!--<p class="c_price">￥<span>{{coupon.voucher_price}}</span></p>-->
              <!--<div class="Choice" v-if="coupon.is_canUse == '1'">-->
              <!--<i class="iconfont icon-pitchon2" v-if="selectedCoupon && coupon.voucher_id == selectedCoupon.voucher_id"></i>-->
              <!--<i class="iconfont icon-pitch2" v-else></i>-->
              <!--</div>-->
              <div v-if="coupon.is_canUse == '1'" style="color: #fff; line-height: 5rem; font-size: 0.8rem; text-align: center" @click="selectCoupon(coupon)">使用</div>
              <div v-else style="color: #fff; line-height: 5rem; text-align: center; font-size: 14px;">
                使用条件不足
              </div>
            </div>
          </div>
        </div>
        <div v-show="!rentInfo.voucher_list || rentInfo.voucher_list.length <= 0" style="margin: 0 auto; margin-top: 5rem; text-align: center">
          当前无可用优惠券~
        </div>
        <div class="c_btn" @click="cancleUseCoupon">不使用优惠券</div>
      </div>
    </div>
    <!--<back-nav></back-nav>-->
    <datetime-picker
      ref="rentDatePicker"
      v-model="currentDate"
      :startDate="$utils.getDay(7)"
      :endDate="$utils.getDay(60)"
      type="date"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      @confirm="handleRentDateChange">
    </datetime-picker>
    <mt-actionsheet
      :actions="actions"
      v-model="sheetVisible">
    </mt-actionsheet>
  </div>
</template>

<script>
  import {mapModules, mapRules} from 'vuet'
  import payPop from '../../../components/payPop/index'
  import DatetimePicker from '../../../components/dateTimePicker'
  import {Actionsheet} from 'mint-ui'
  import * as request from '../../../request'

  export default{
    mixins: [
//      mapModules({addressList: 'addressList', selectedCartIdList: 'selectedCartIdList'}),
//      mapRules({once: ['addressList', 'selectedCartIdList']})
      mapModules({addressList: 'addressList', shopAddressList: 'shopAddressList'}),
      mapRules({once: ['addressList', 'shopAddressList']})
    ],
    beforeRouteEnter (to, from, next) {
      request.getCouponSetting().then(data => {
        next(vm => {
          vm.couponSetting = data
        })
      }).catch(e => {
        console.error('获取积分设置失败', e)
        next()
      })
    },
    data() {
      return {
        type: this.$route.query.type || 0, // 0 邮寄 1 自提
        from: '',
        rentInfo: {total: 0, integral: 0, balance: 0, alldata: [], voucher_list: []},
        couponModelShow: false,
        selectedCoupon: null, //  选择使用的优惠券
        couponSetting: {points_money: 0, points_orderrate: 0},
        useIntegral: false,
        useBalance: false,
        remark: '', // 备注
        order: {order_id: '', pay_sn: ''}, // 提交成功后，对其赋值
        selectedCartIdList: [], // 要购买的商品的cartId列表
        rentInfoEdit: {
          date: '点击选择时间',
          trade: '', // 所属行业
          place: '', // 摆放场景
          company: '', // 公司名
          tel: '', // 联系电话
          square: '', // 面积
          placeImg: [], // 场地图片
          rentTerm: '', // 租期
          installment: 0 // 分期数
        },
        currentDate: new Date(),
        sheetVisible: false,
        actions: [{
          name: '拍照',
          method: this.getFromCamera
        }, {
          name: '从相册选取',
          method: this.getFromAlbum
        }]
      }
    },
    components: {
      'mt-actionsheet': Actionsheet,
      'datetimePicker': DatetimePicker
    },
    computed: {
      canUseCouponNum () {
        let num = 0
        for (let i = 0; i < this.rentInfo.voucher_list.length; i++) {
          if (this.rentInfo.voucher_list[i].is_canUse) {
            num++
          }
        }
        return num
      },
      // 抵扣的余额
      balanceUsed () {
        let balanceMony = parseFloat(parseFloat(this.rentInfo.balance).toFixed(2))
        let totalMony = parseFloat(parseFloat(this.rentInfo.total).toFixed(2))
        let remain = totalMony
        if (this.useIntegral) {
          remain = parseFloat((totalMony - this.integralUsed).toFixed(2))
        }
        return balanceMony > remain ? remain : balanceMony
      },
      // 抵扣的积分金额
      integralUsed () {
        let rentTotal = this.rentInfo.total * this.rentInfoEdit.rentTerm + parseFloat(this.rentInfo.shipping_fee)
        let integralMoney = this.rentInfo.integral * this.couponSetting.points_money
//        let canIntegralMoney = parseInt((parseFloat(rentTotal) * this.couponSetting.points_orderrate).toFixed(2)) // 最多可使用积分抵扣的金额
        let canIntegralMoney = parseInt(parseFloat(rentTotal) * this.couponSetting.points_orderrate / this.couponSetting.points_money) * this.couponSetting.points_money // 最多可使用积分抵扣的金额
        return integralMoney > canIntegralMoney ? canIntegralMoney : integralMoney
      },
      // 押金(两个月的租金)
      deposit() {
        if (this.rentInfoEdit.rentTerm == '') {
          return ''
        }
        return (this.rentInfo.total * 2).toFixed(2)
      },
      // 扣除优惠券 积分抵扣后的订单额（不包含押金）
      orderTotalMoney () {
        if (this.rentInfoEdit.rentTerm == '') {
          return ''
        }
        let priceOrigin = this.rentInfo.total * this.rentInfoEdit.rentTerm + parseFloat(this.rentInfo.shipping_fee)
        let priceNow = priceOrigin
        if (this.useIntegral) {
          priceNow = priceNow - this.integralUsed
        }
        if (this.useBalance) {
          priceNow = priceNow - this.balanceUsed
        }
        if (this.selectedCoupon) { // 使用了优惠券
          priceNow = priceNow - this.selectedCoupon.voucher_price
        }
        return priceNow
      },
      // 每期价格
      installmentMoney() {
        if (this.rentInfoEdit.installment == 0) {
          return ''
        }
        return this.orderTotalMoney / this.rentInfoEdit.installment
      },
      // 最后需支付的金额（包含押金）
      payed () {
        if (this.orderTotalMoney == '') {
          return ''
        }
        let payed = this.orderTotalMoney
        if (this.rentInfoEdit.installment != 0) { // 有分期， 需支付 = 每期金额 + 押金
          payed = parseFloat(this.installmentMoney) + parseFloat(this.deposit)
        } else { // 无分期， 需支付 = 抵扣后的订单额 + 押金
          payed = parseFloat(this.deposit) + parseFloat(this.orderTotalMoney)
        }
        if (payed < 0) {
          payed = 0
        }
        return payed
      },
      address () {
        if (this.$route.query.addressId) {
          for (let i = 0; i < this.addressList.data.length; i++) {
            if (this.addressList.data[i].address_id == this.$route.query.addressId) {
              return this.addressList.data[i] // 使用指定地址
            }
          }
        } else {
          for (let i = 0; i < this.addressList.data.length; i++) {
            if (this.addressList.data[i].is_default === '1') {
              return this.addressList.data[i] // 使用默认地址
            }
          }
          if (this.addressList.data.length > 0) {
            return this.addressList.data[0] // 没有默认地址，使用第一个地址
          }
        }
        return {} // 没有地址
      },
      shopAddress () {
        if (this.$route.query.shopAddressId) {
          for (let i = 0; i < this.shopAddressList.data.length; i++) {
            if (this.shopAddressList.data[i].address_id == this.$route.query.shopAddressId) {
              return this.shopAddressList.data[i] // 使用指定地址
            }
          }
        } else {
          for (let i = 0; i < this.shopAddressList.data.length; i++) {
            if (this.shopAddressList.data[i].is_default === '1') {
              return this.shopAddressList.data[i] // 使用默认地址
            }
          }
          if (this.shopAddressList.data.length > 0) {
            return this.shopAddressList.data[0] // 没有默认地址，使用第一个地址
          }
        }
        return {} // 没有地址
      }
    },
    beforeRouteLeave  (to, from, next) {
      this.$indicator.close()
      next()
    },
    created() {
//      this.getCouponSetting()
      // this.$native.weixinShare(window.location.href)
//      if (this.from === 'address-list' || this.from === 'address-add') {  // 选择地址页跳回
//        return
//      }
      console.log('query', this.$route.query.cart)
      this.selectedCartIdList = this.$route.query.cart.toString().split(',')
      console.log('cartIdList', this.$route.query, this.selectedCartIdList)
      this.getRentInfo(this.selectedCartIdList)
    },
    mounted() {
      this.$native.weixinShare(window.location.href, '遇花园', null, '')
    },
    watch: {
      $route () {
        this.type = this.$route.query.type
      },
      selectedCoupon: function (newVal) {
        if (newVal) {
          this.useIntegral = false
        }
      }
    },
    methods: {
      ifValidInstallMonth(rentMonth, installMonth) {
        if (!rentMonth || !installMonth) {
          return false
        }
        return (rentMonth / installMonth) % 3 == 0
      },
      switchCouponShow(boolValue) {
        this.couponModelShow = boolValue
      },
//      getCouponSetting() {
//        this.$request.getCouponSetting().then(data => {
//          this.couponSetting = data
//        })
//      },
      cancleUseCoupon() {
        this.selectedCoupon = null
        this.switchCouponShow(false)
      },
      switchSelectCoupon(coupon) {
        if (coupon.is_canUse == '0') {
          return
        }
        this.selectedCoupon = coupon
      },
      switchType(value) {
        this.$router.replace({
          name: 'order-rent-confirm',
          query: {cart: this.$route.query.cart, type: value}
        })
      },
      switchUseBalance(boolValue) {
        this.useBalance = boolValue
      },
      switchIntegral(boolValue) {
        this.useIntegral = boolValue
      },
      openRentDatePicker() {
        this.$refs.rentDatePicker.open()
      },
      handleRentDateChange(value) {
        let date = new Date(value)
        let dateStr = this.$utils.formatDate(date, 'yyyy-MM-dd')
        this.rentInfoEdit.date = dateStr
        console.log(dateStr)
      },
      gotoAddAddress() {
        this.$router.push({
          name: 'address-add',
          query: {from: 'order-rent-confirm', cart: this.$route.query.cart, type: this.type}
        })
      },
      getRentInfo(idList) {
        this.$request.getRentInfo(idList).then(data => {
          this.rentInfo = data
        })
      },
      selectAddress() {
        this.$router.push({
          name: 'address-list',
          query: {from: 'order-rent-confirm', cart: this.$route.query.cart, type: this.type}
        })
      },
      selectShopAddress() {
        this.$router.push({
          name: 'address-shop',
          query: {from: 'order-rent-confirm', cart: this.$route.query.cart, type: this.type}
        })
      },
      submitOrder() {
        if (this.rentInfoEdit.date == '点击选择时间') {
          this.$toast('请选择期望入驻时间')
          return
        }
//        if (this.rentInfoEdit.trade == '') {
//          this.$toast('请选择所属行业')
//          return
//        }
//        if (this.rentInfoEdit.place == '') {
//          this.$toast('请选择摆放场景')
//          return
//        }
//        if (this.rentInfoEdit.company == '') {
//          this.$toast('请输入公司名称')
//          return
//        }
//        if (!this.$validator.phone(this.rentInfoEdit.tel)) {
//          this.$toast('请输入联系电话')
//          return
//        }
//        if (this.rentInfoEdit.square == '') {
//          this.$toast('请输入场地面积')
//          return
//        }
//        if (this.rentInfoEdit.place == '') {
//          this.$toast('请上传场地实景图')
//          return
//        }
        if (this.rentInfoEdit.rentTerm == '') {
          this.$toast('请选择租用时长')
          return
        }
        if (parseInt(this.rentInfoEdit.installment) > parseInt(this.rentInfoEdit.rentTerm)) {
          this.$toast('付款分期期数不能高于租用时长')
          return
        }
        let param = {
          cart_id: this.selectedCartIdList,
          ifcart: 1,
          is_balance: this.useBalance ? 1 : 0,
          is_integral: this.useIntegral ? 1 : 0,
          order_note: this.remark,
          pay_name: 'online',
          self: this.type,
          r_company: this.rentInfoEdit.company,
          r_connect: this.rentInfoEdit.tel,
          r_images: this.rentInfoEdit.placeImg,
          r_industry: this.rentInfoEdit.trade,
          r_ins_num: this.rentInfoEdit.installment,
          r_is_installment: this.rentInfoEdit.installment == '0' ? 0 : 1,
          r_rent_time: this.rentInfoEdit.rentTerm,
          r_scene: this.rentInfoEdit.place,
          r_square: this.rentInfoEdit.square,
          r_time: this.rentInfoEdit.date,
          voucher_id: this.selectedCoupon && this.selectedCoupon.voucher_id
        }
        console.log('租花参数', param)
        if (this.type == 0) { // 邮寄
          param.address_id = this.address.address_id
        } else if (this.type == 1) { // 自提
          param.address_id = this.shopAddress.address_id
        }
        if (!param.address_id) {
          this.$toast('请先选择地址')
          return
        }
        this.$request.submitRentOrder(param).then(data => {
//          this.$toast('提交订单成功')
          this.selectedCartIdList = []
          this.order = data
          console.log(this.order)
          if (parseFloat(parseFloat(this.payed).toFixed(2)) - 0 <= 0) { // 通过帐号余额支付，不需要走第三方支付
            this.$router.replace({name: 'order-success', query: {id: this.order.order_id, type: '2'}})
            return
          }
          let paySn = this.order.pay_sn
          payPop({paySn: paySn, orderId: this.order.order_id}, this.canclePay)
        }).catch(e => {
          this.$toast('订单提交失败:' + e.msg)
        })
      },
      canclePay() {
        this.$router.replace({name: 'order-rent-detail', params: {id: this.order.order_id}})
      },
      delImg(index) {
        this.$messageBox.confirm('确定删除图片?').then(action => {
          this.rentInfoEdit.placeImg.splice(index, 1)
        }).catch(() => {
        })
      },
      getImg() {
        console.log('click click')
        if (this.rentInfoEdit.placeImg.length >= 6) {
          this.$toast('只能选择6张图片~')
          return
        }
        let deviceType = this.$utils.getDeviceType()
        if (deviceType == 'wx-iPhone' || deviceType == 'wx-Android') {
          let wxImgPromiseList = []
          wx.chooseImage({ // eslint-disable-line
            count: 6 - this.rentInfoEdit.placeImg.length, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              for (let i = 0; i < res.localIds.length; i++) {
                var localId = res.localIds[i]
                let promise = this.$utils.wxGetLocalImgData(localId)
                wxImgPromiseList.push(promise)
              }
              Promise.all(wxImgPromiseList).then((imgList) => {
                this.$indicator.open('上传图片中...')
                this.$request.uploadImg(imgList).then(data => {
                  this.rentInfoEdit.placeImg = [...this.rentInfoEdit.placeImg, ...data]
                }).catch(e => {
                  this.$toast('上传图片失败:' + e.msg)
                }).finally(() => {
                  this.$indicator.close()
                })
              })
            }
          })
        } else if (deviceType == 'iPhone') {
          this.getFromAlbum() // 因为iphone不带capture属性的input 点击后本身就会弹出选择图库或拍照
        } else {
          this.sheetVisible = true
        }
      },
      getFromCamera() {
        var imgInputFile = document.getElementById('fileInput1')
        if (!imgInputFile.hasAttribute('capture')) {
          imgInputFile.setAttribute('capture', 'camera')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      getFromAlbum() {
        var imgInputFile = document.getElementById('fileInput1')
        if (imgInputFile.hasAttribute('capture')) {
          imgInputFile.removeAttribute('capture')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      clearInputFile() {
        var self = this
        var selectPic = document.getElementById('select-pic')
        var randomStr = Math.random().toString(36)
        selectPic.innerHTML = '<input id="fileInput1" type="file" title="" ' + randomStr + '"  accept="image/jpeg,image/jpg,image/png,image/gif"  id="fileInput1" style="visibility: hidden" >'
        document.getElementById('fileInput1').addEventListener('change', self.fileSelected)
      },
      fileSelected(e) {
        try {
          var reader = new window.FileReader()
          reader.onload = (e) => {
            if (e.total > 1024 * 1024 * 5) {
              this.$toast('图片大小不能超过5M')
              return
            }
            // 调用图片压缩方法
            // console.log("成功加载图片，开始压缩图片...")
            this.$utils.compress(e.target.result, (imgDataUrl) => {
              // todo 调用上传图片接口
              this.$request.uploadImg(imgDataUrl).then(data => {
                this.rentInfoEdit.placeImg.push(data[0])
              }).catch(e => {
                this.$toast('上传图片失败:' + e.msg)
              })
            })
          }
          // 选取同名文件不会再次触发change事件，所以在加载后替换input控件
          reader.onloadend = (e) => {
            this.clearInputFile()
          }
          reader.readAsDataURL(e.target.files[0])
        } catch (e) {
          console.log('读取图片文件发生了错误')
          console.log(e)
        }
      },
      selectCoupon(coupon) {
        this.selectedCoupon = coupon
        this.switchCouponShow(false)
      }
    }
  }
</script>

<style>
  .coupon-selected{
    border: 1px solid #3fbc6e;
  }
  .Fillinformation .Fill_input .OtherInfo li {
    font-size: 14px;
    /*padding-left: .5rem;*/
    /*height: 45px;*/
    /*line-height: 45px;*/
    color: #051b28;
    /*background: #fff;*/
    /*position: relative;*/
    margin-top: .25rem;
    /*border-bottom: #dcdddd solid 1px;*/
    /*overflow: hidden;*/
  }

  .coupon_box .icon-pitchon2 {
    display: block;
    width: 3rem;
    line-height: 34px;
    text-align: right;
    color: white !important;
    font-size: 20px;
  }

  .coupon_box .icon-pitch2 {
    display: block;
    width: 3rem;
    line-height: 34px;
    text-align: right;
    color: #aaa;
    font-size: 24px;
  }
</style>
